<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="学员姓名">
        <el-input v-model="queryParams.name" placeholder="学员姓名" clearable />
      </el-form-item>
      <el-form-item label="学历">
        <el-select v-model="queryParams.degree" placeholder="学历" clearable>
          <el-option label="初中" :value="1" />
          <el-option label="高中" :value="2" />
          <el-option label="大专" :value="3" />
          <el-option label="本科" :value="4" />
          <el-option label="硕士" :value="5" />
          <el-option label="博士" :value="6" />
        </el-select>
      </el-form-item>
      <el-form-item label="班级">
        <el-select v-model="queryParams.clazzId" placeholder="班级" clearable>
          <el-option
            v-for="clazz in clazzList"
            :key="clazz.id"
            :label="clazz.name"
            :value="clazz.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="handleAdd">添加学员</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="studentList" 
      fit
      style="width: 100%"
      :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
    >
      <el-table-column type="index" label="序号" width="80" header-align="center" align="center" />
      <el-table-column prop="name" label="姓名" min-width="120" header-align="center" align="center" />
      <el-table-column prop="no" label="学号" min-width="150" header-align="center" align="center" />
      <el-table-column prop="gender" label="性别" width="80" header-align="center" align="center">
        <template #default="scope">
          {{ scope.row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="degree" label="学历" min-width="120" header-align="center" align="center">
        <template #default="scope">
          {{ formatDegree(scope.row.degree) }}
        </template>
      </el-table-column>
      <el-table-column prop="clazzName" label="班级" min-width="180" header-align="center" align="center" />
      <el-table-column prop="violationScore" label="违纪扣分" width="100" header-align="center" align="center" />
      <el-table-column label="操作" width="240" header-align="center" align="center" fixed="right">
        <template #default="scope">
          <el-button size="small" type="warning" @click="handleViolation(scope.row)"
            >违纪处理</el-button
          >
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
      @close="resetForm"
    >
      <el-form ref="studentForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="学号" prop="no">
          <el-input v-model="form.no" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="学历" prop="degree">
          <el-select v-model="form.degree" placeholder="请选择学历">
            <el-option label="初中" :value="1" />
            <el-option label="高中" :value="2" />
            <el-option label="大专" :value="3" />
            <el-option label="本科" :value="4" />
            <el-option label="硕士" :value="5" />
            <el-option label="博士" :value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="clazzId">
          <el-select v-model="form.clazzId" placeholder="请选择班级">
          <el-option
            v-for="clazz in clazzList"
            :key="clazz.id"
            :label="clazz.name"
            :value="clazz.id"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" />
        </el-form-item>
        <el-form-item label="院校学生">
          <el-switch v-model="form.isCollege" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="联系地址">
          <el-input v-model="form.address" type="textarea" />
        </el-form-item>
        <el-form-item label="毕业时间">
          <el-date-picker
            v-model="form.graduationDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 违纪处理对话框 -->
    <el-dialog
      v-model="violationDialogVisible"
      title="违纪处理"
      width="30%"
    >
      <el-form :model="violationForm" label-width="100px">
        <el-form-item label="学员姓名">
          <el-input v-model="violationForm.studentName" disabled />
        </el-form-item>
        <el-form-item label="当前扣分">
          <el-input v-model="violationForm.currentScore" disabled />
        </el-form-item>
        <el-form-item label="扣除分数" prop="score">
          <el-input-number v-model="violationForm.score" :min="1" :max="10" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="violationDialogVisible = false">取消</el-button>
          <el-button type="warning" @click="submitViolation">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listStudents,
  addStudent,
  updateStudent,
  deleteStudent,
  getStudentById,
  handleStudentViolation
} from '@/api/stu'
import { listAllClazzs } from '@/api/clazz'

// 查询参数
const queryParams = ref({
  name: '',
  degree: null,
  clazzId: null,
  page: 1,
  pageSize: 10
})

// 表单数据
const form = ref({
  id: null,
  name: '',
  no: '',
  gender: 1,
  phone: '',
  degree: null,
  clazzId: null,
  idCard: '',
  isCollege: 0,
  address: '',
  graduationDate: ''
})

// 违纪表单
const violationForm = ref({
  studentId: null,
  studentName: '',
  currentScore: 0,
  score: 1
})

// 表单验证规则
const rules = ref({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  no: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { 
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur'
    }
  ],
  degree: [{ required: true, message: '请选择学历', trigger: 'change' }],
  clazzId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  idCard: [
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入正确的身份证号',
      trigger: 'blur'
    }
  ]
})

const studentList = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const violationDialogVisible = ref(false)
const dialogTitle = ref('')
const studentForm = ref(null)
const clazzList = ref([])

// 学历格式化
const formatDegree = (degree) => {
  const degreeMap = {
    1: '初中',
    2: '高中',
    3: '大专',
    4: '本科',
    5: '硕士',
    6: '博士'
  }
  return degreeMap[degree] || '未知'
}

// 获取学员列表
const getList = async () => {
  try {
    const res = await listStudents(queryParams.value)
    if (res.code === 1) {
      studentList.value = res.data.rows
      total.value = res.data.total
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取学员列表失败')
  }
}

// 获取班级列表
const getClazzList = async () => {
  try {
    const res = await listAllClazzs()
    if (res.code === 1) {
      clazzList.value = res.data
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取班级列表失败')
  }
}

// 查询
const handleQuery = () => {
  queryParams.value.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    name: '',
    degree: null,
    clazzId: null,
    page: 1,
    pageSize: 10
  }
  getList()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.value.page = val
  getList()
}

// 添加学员
const handleAdd = () => {
  dialogTitle.value = '添加学员'
  dialogVisible.value = true
  nextTick(() => {
    studentForm.value?.clearValidate()
  })
}

// 编辑学员
const handleEdit = async (row) => {
  try {
    const res = await getStudentById(row.id)
    if (res.code === 1) {
      form.value = { ...res.data }
      dialogTitle.value = '编辑学员'
      dialogVisible.value = true
      nextTick(() => {
        studentForm.value?.clearValidate()
      })
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取学员信息失败')
  }
}

// 违纪处理
const handleViolation = (row) => {
  violationForm.value = {
    studentId: row.id,
    studentName: row.name,
    currentScore: row.violationScore,
    score: 1
  }
  violationDialogVisible.value = true
}

// 删除学员
const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该学员吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deleteStudent(row.id)
        if (res.code === 1) {
          ElMessage.success('删除成功')
          getList()
        }
      } catch (error) {
        console.error(error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 提交表单
const submitForm = async () => {
  await studentForm.value.validate()
  try {
    if (form.value.id) {
      // 编辑
      const res = await updateStudent(form.value)
      if (res.code === 1) {
        ElMessage.success('修改成功')
        dialogVisible.value = false
        getList()
      }
    } else {
      // 添加
      const res = await addStudent(form.value)
      if (res.code === 1) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        getList()
      }
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('操作失败')
  }
}

// 提交违纪处理
const submitViolation = async () => {
  try {
    const res = await handleStudentViolation(
      violationForm.value.studentId, 
      violationForm.value.score
    )
    if (res.code === 1) {
      ElMessage.success('处理成功')
      violationDialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('违纪处理失败')
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    id: null,
    name: '',
    no: '',
    gender: 1,
    phone: '',
    degree: null,
    clazzId: null,
    idCard: '',
    isCollege: 0,
    address: '',
    graduationDate: ''
  }
}

onMounted(() => {
  getList()
  getClazzList()
})
</script>

<style scoped>
.app-container {
  padding: 24px;
  background-color: #f8fafc;
  min-height: calc(100vh - 50px);
}

.demo-form-inline {
  background: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.el-table {
  margin-top: 24px;
  font-size: 14px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  overflow: hidden;
  :deep(.el-table__header-wrapper .el-table__cell) {
    background-color: #f5f7fa;
  }
  :deep(.el-table__cell) {
    padding: 12px 0;
  }
}

.el-table :deep(.el-table__cell) {
  padding: 14px 0;
}

.el-button {
  transition: all 0.3s;
  border-radius: 8px;
  padding: 10px 20px;
}

.el-button + .el-button {
  margin-left: 12px;
}

.pagination-container {
  margin-top: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.05);
  text-align: center;
}

.el-dialog {
  border-radius: 16px;
}

.el-dialog__body {
  padding: 24px 24px 12px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input,
.el-select,
.el-textarea {
  border-radius: 8px;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
</style>
